package com.scud.product.listener;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.scud.client.order.IOrderClient;
import com.scud.common.constants.RabbitmqConstants;
import com.scud.model.order.dto.FullOrderDto;
import com.scud.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author vermouth
 */
@Component
@Slf4j
public class RabbitmqListener {
    @Autowired
    private ProductService productService;
    @Autowired
    private IOrderClient orderClient;
    /**
     * 订单异步处理
     * @param message:
     * @param channel:
     * @param tag:
     * @return void
     */
    @RabbitListener(queues = RabbitmqConstants.SCUD_ORDER_QUEUE)
    public void orderListener(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){
        //在此完成数据库中商品SKU相关信息的更改
        FullOrderDto orderDto = JSONObject.parseObject(message, FullOrderDto.class);

        //完善orderDto中的数据
        orderDto = productService.completeInfo(orderDto);

        //商品SKU相关信息的更改
        Map<Long, Integer> skuCount = orderDto.getSkuCount();
        productService.deductStock(skuCount);

        //feign调用order子系统添加订单
        orderDto.setSkuCount(null);
        orderClient.createOrder(orderDto);

        try {
            channel.basicAck(tag,false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
